package sz.szsmk.citizencard.mvp.presenter;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import javax.inject.Inject;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.RxSubscribers;
import sz.szsmk.citizencard.model.network.bean.request.UserBehaviorBrowseReq;
import sz.szsmk.citizencard.model.network.bean.request.VerifyBindNgUserReq;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckIsChargeRes;
import sz.szsmk.citizencard.model.network.bean.response.VerifyBindNgUserRes;
import sz.szsmk.citizencard.model.network.dzbean.req.CommonRequest;
import sz.szsmk.citizencard.model.network.dzbean.req.GetOpenIdReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThiedReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.req.QueryDzsmkAgreementReq;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.QueryDzsmkAgreeMentRes;
import sz.szsmk.citizencard.mvp.contract.IMainContact;
import sz.szsmk.citizencard.mvp.contract.IPureTextWebViewContact;
import sz.szsmk.citizencard.retrofitrxjava.DZSmkAppInit;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource;
import sz.szsmk.citizencard.ui.fragment.ElecCardSignDialog;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.ObjectSignatureUtil;
import sz.szsmk.citizencard.widget.GlobalVariables;
import sz.szsmk.citizencard.widget.PureTextWebViewActivity;

/**
 * author : hyt
 * date : 2020/1/7
 * description :
 */
public class PureTextWebViewPresenter extends IBasePresenter  implements IPureTextWebViewContact.IPureTextWebViewPresenter<IPureTextWebViewContact.IPureTextWebView> {
    private NetworkDateSources mNetworkDate;
    private NetworkDateSource mNetworkDateSource;
    GsdxNetApi gsdxNetApi;

    private GetOpenIdRes getOpenIdRes;

    @Inject
    public PureTextWebViewPresenter( GsdxNetApi gsdxNetApi) {
        this.gsdxNetApi = gsdxNetApi;
        this.mNetworkDate = NetworkDateSources.getInstance();
        this.mNetworkDateSource = NetworkDateSource.getInstance();
    }

    @Override
    public void onQRbuyCar(Context context) {
        GetOpenIdReq getOpenIdReq = new GetOpenIdReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        getOpenIdReq.setUser_type(0);
        getOpenIdReq.setAccess_token(access_token);
        String s = new Gson().toJson(getOpenIdReq);
        L.e(Constant.TAG, "getOpenid----" + s);
        gsdxNetApi.getOpenId(getOpenIdReq)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscribers<GetOpenIdRes>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    protected void _onNext(GetOpenIdRes response) {
                        getOpenIdRes = response;
                        String json = new Gson().toJson(response);
                        L.e(Constant.TAG, "getOpenId---->" + json);
                        String openId = response.getOpenId();
                        ACache.get(DaggerApplication.getIns()).remove("openId");
                        ACache.get(DaggerApplication.getIns()).put("openId", openId + "");
                        ACache.get(DaggerApplication.getIns()).put("userId", response.getUserId() + "");
                        PreAuthResult preAuthResult = new PreAuthResult();
                        preAuthResult.setOpenId(response.getOpenId());
                        GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);

                        if (response.getCode().equals("000000")) {
                            checkIsOpenElecCard(context,ACache.get(context).getAsString("openId"));
                        } else {
                            onFail(response.getMessage());
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        Log.e("zdh", "请求失败" + message);
                    }
                });
    }

    public void checkIsOpenElecCard(Context context, String openId) {

        CommonRequest request = new CommonRequest();
        request.setOpenId(openId);
        ObjectSignatureUtil.signaturePreAuthRequest(request);
        String toJson = new Gson().toJson(request);
        L.e(Constant.TAG, "checkIsRealName------>" + toJson);
        mNetworkDateSource.checkIsRealName(request, new Action1<CheckIsRealNameRes>() {
            @Override
            public void call(CheckIsRealNameRes preAuthRes) {
                if (preAuthRes.getCode().equals("0000")) {
                    checkIsOpenElecCardSuccess(context,preAuthRes);

                } else {
                    onFail(preAuthRes.getMessage());
                }
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                L.e(Constant.TAG, "--------------------" + throwable.getMessage());
            }
        });
    }

    private void checkIsOpenElecCardSuccess(Context context, CheckIsRealNameRes loginResponse){
        String openId = ACache.get(context).getAsString("openId");
        //4.已实名，判断是否已首冲  未实名 弹窗去实名
        if (loginResponse != null) {
            String isRealName = loginResponse.getData().getIsRealName();
            if (isRealName.equals("0")) {

                ACache.get(DaggerApplication.getIns()).put("channelId", "000001");
                preAuthThird(openId, "1");

            } else if (isRealName.equals("1")) {
                queryDzsmkAgreement(context,openId);
            }
        }
    }

    public void preAuthThird(String openId,String id) {
        PreAuthThiedReq preAuthThiedReq = new PreAuthThiedReq();
        preAuthThiedReq.setMobileNumber(getOpenIdRes.getMobile() + "");
        preAuthThiedReq.setOpenId(openId);
        preAuthThiedReq.setUserId(getOpenIdRes.getUserId() + "");
        preAuthThiedReq.setPhotoUrl("");
        String channelId = ACache.get(DaggerApplication.getIns()).getAsString("channelId");
        preAuthThiedReq.setChannelId(channelId);

        ObjectSignatureUtil.signaturePreAuthRequest(preAuthThiedReq);
        String toJson = new Gson().toJson(preAuthThiedReq);
        L.e(Constant.TAG, "------->" + toJson);
        mNetworkDateSource.preAuthThird(preAuthThiedReq, new Action1<PreAuthThirdRes>() {
            @Override
            public void call(PreAuthThirdRes preAuthRes) {
                String code = preAuthRes.getCode();
                if (code.equals("0000")) {
                    PreAuthThirdRes.DataBean data = preAuthRes.getData();
                    String json = new Gson().toJson(data);
                    ACache.get(DaggerApplication.getIns()).put("token", preAuthRes.getData().getToken());
                    PreAuthResult preAuthResult = new Gson().fromJson(json, PreAuthResult.class);
                    GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                    PreAuthResult authResult = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult();
                    String token = authResult.getToken();


                    (( IPureTextWebViewContact.IPureTextWebView) mView).onQRbuyCarSuccess(id);
                    L.e(Constant.MTAG, "存储的token：" + token);

                } else {
                    onFail(preAuthRes.getMessage());
                }
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                L.e(Constant.TAG, "--------------------" + throwable.getMessage());
            }
        });
    }

    public void queryDzsmkAgreement(Context context, final String openId) {
        QueryDzsmkAgreementReq queryDzsmkAgreementReq = new QueryDzsmkAgreementReq();
        queryDzsmkAgreementReq.setOpenId(openId);
        queryDzsmkAgreementReq.setUserType(0);
        String json = new Gson().toJson(queryDzsmkAgreementReq);
        L.e(Constant.TAG, "queryDzsmkAgreement---->" + json);
        mNetworkDate.queryDzsmkAgreement(queryDzsmkAgreementReq, new SubscribeResult<QueryDzsmkAgreeMentRes>() {
            @Override
            protected void onOk(QueryDzsmkAgreeMentRes response) {
                String toJson = new Gson().toJson(response);
                String channelId = response.getChannelId();
                ACache.get(DaggerApplication.getIns()).put("channelId", channelId);
                L.e(Constant.TAG, "queryDzsmkAgreement---->" + toJson);
                preAuthThird(openId, "2");
            }

            @Override
            protected void onFailure(QueryDzsmkAgreeMentRes response) {
                super.onFailure(response);
                if (response.getCode().equals("000005")) {
                    ACache.get(DaggerApplication.getIns()).put("channelId", "000003");
                    preAuthThird(openId, "2");
                }
                onFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    private void onFail(String msg){
        ((IPureTextWebViewContact.IPureTextWebView)mView).onFail(msg);
    }


    @Override
    public void checkIsCharge() {
        CommonRequest commonRequest = new CommonRequest();
        String openId = ACache.get(DaggerApplication.getIns()).getAsString("openId");
        commonRequest.setOpenId(openId);

        ObjectSignatureUtil.signatureZhsz(commonRequest, "");
        String json = new Gson().toJson(commonRequest);
        L.e(Constant.TAG, "checkIsCharge-----" + json);
        mNetworkDateSource.checkIsCharge(commonRequest, new Action1<CheckIsChargeRes>() {
            @Override
            public void call(CheckIsChargeRes ibaseBean) {


                ((IPureTextWebViewContact.IPureTextWebView) mView).checkIsChargeSucc(ibaseBean);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    @Override
    public void userBehaviorBrowse(int id) {
        UserBehaviorBrowseReq userBehaviorBrowseReq = new UserBehaviorBrowseReq();
        userBehaviorBrowseReq.setModularId(id);
        userBehaviorBrowseReq.setAccessToken(ACache.get(DaggerApplication.getIns()).getAsString("access_token"));

        mNetworkDateSource.userBehaviorBrowse(userBehaviorBrowseReq, new Action1<BaseBean>() {
            @Override
            public void call(BaseBean baseBean) {

                L.e(Constant.TAG, "ok----->" );
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }


}
